package com.example.pda.common;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.example.pda.data.Result;
import com.example.pda.net.Api;
import com.example.pda.net.ApiException;
import com.example.pda.net.HttpManager;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class BaseViewModel extends ViewModel {

    public Api api;

    public MutableLiveData<String> dialogMsg = new MutableLiveData<>();
    public MutableLiveData<Boolean> showDialog = new MutableLiveData<>();
    public MutableLiveData<String> toast = new MutableLiveData<>();

    public MutableLiveData<String> getDialogMsg() {
        return dialogMsg;
    }

    public MutableLiveData<Boolean> getShowDialog() {
        return showDialog;
    }

    public MutableLiveData<String> getToast() {
        return toast;
    }

    public BaseViewModel() {
        api = HttpManager.getInstance().getApi();
    }

    @SuppressLint("CheckResult")
    public <T> void enqueue(Observable<Result<T>> observable, boolean isShow, ResultCallback<T> callback) {
        getShowDialog().setValue(isShow);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<T>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Result<T> t) {
                        if (t.isSuccess()) {
                            callback.onSuccess(t.getData());
                        } else {
                            if ("500".equals(t.getCode()) && TextUtils.isEmpty(t.getMsg())) {
                                callback.onError(0, "接口未知异常");
                                return;
                            }
                            callback.onError(0, t.getMsg());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ApiException apiException = ApiException.handleException(e);
                        callback.onError(apiException.getCode(), apiException.getMessage());
                        getShowDialog().setValue(false);
                    }

                    @Override
                    public void onComplete() {
                        getShowDialog().setValue(false);
                    }
                });
    }

    public interface ResultCallback<T> {
        void onSuccess(T t);

        void onError(int code, String msg);
    }

}
